package com.mofofa.maozy.info

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.mofofa.maozy.ProjectApplication
import com.mofofa.maozy.base.BaseViewModel
import com.mofofa.maozy.components.dialog.PopListItem
import com.mofofa.maozy.data.*
import com.mofofa.maozy.enums.InfoPageActionEnum
import com.mofofa.maozy.network.ApiUserReposity
import com.mofofa.maozy.utils.InfoProcessUtil
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.mofofa.maozy.utils.UsageCountryUtil
import com.mofofa.maozy.utils.UserStateUtil
import org.json.JSONArray
import org.json.JSONObject
import java.nio.charset.Charset

class InfoViewModel : BaseViewModel() {

    //页面选项模块-步骤栏
    val mMaozyInfoMaozyStepMaozyList = mutableListOf<PopListItem>()

    //页面选项模块-输入条目
    var mMaozyInfoMaozyFieldMaozyList = mutableListOf<RevObjInfoPageFieldConfig>()

    //页面选项模块-当前配置
    var mMaozyCurrentMaozyPageMaozyConfig = DataInfoPageConfig()

    //银行卡模块
    val mMaozyBankMaozyCodeMaozyList = mutableListOf<PopListItem>()

    //基本信息模块
    var mMaozyState: String = ""
    var mMaozyCity: String = ""
    var mMaozyArea: String = ""
    val mMaozyStateMaozyList = mutableListOf<PopListItem>()
    val mMaozyCityMaozyList = mutableListOf<PopListItem>()
    val mMaozyAreaMaozyList = mutableListOf<PopListItem>()
    var mMaozyCityMaozyJsonMaozyArray: JSONArray? = null

    //页面配置初始化完成回调
    val onMaozyInitMaozyPageMaozyConfigMaozyFinishMaozyLiveData =
        MutableLiveData<DataInfoPageConfig>()

    //页面所有认证步骤完成回调
    val onMaozyAllMaozyPageMaozyConfigMaozyFinishMaozyLiveData =
        MutableLiveData<Boolean>()

    //保存页面认证步骤回调
    private val mMaozySaveMaozyInfoMaozyLiveData =
        MutableLiveData<ReqSaveInfo>()

    //查询银行列表回调
    private val mMaozyFetchMaozyBankMaozyCodeMaozyListMaozyLiveData =
        MutableLiveData<ReqGetBankList>()

    //保存页面认证步骤回调
    val onMaozySaveMaozyInfoMaozyLiveData =
        Transformations.switchMap(mMaozySaveMaozyInfoMaozyLiveData) { query ->
            ApiUserReposity.saveMaozyInfo(
                this,
                query.targetUrl,
                query.generateMaozyParams()
            )
        }

    //查询银行列表回调
    val onMaozyFetchMaozyBankMaozyCodeMaozyListMaozyLiveData =
        Transformations.switchMap(
            mMaozyFetchMaozyBankMaozyCodeMaozyListMaozyLiveData
        ) { query ->
            ApiUserReposity.fetchMaozyBankMaozyCodeMaozyList(this, query)
        }

    //保存页面认证步骤
    fun saveMaozyInfo(reqSaveInfo: ReqSaveInfo) {
        mMaozySaveMaozyInfoMaozyLiveData.value = reqSaveInfo
    }

    //查询银行列表
    fun fetchMaozyBankMaozyCodeMaozyList(vvywc2puzerdzxubqcww: ReqGetBankList) {
        mMaozyFetchMaozyBankMaozyCodeMaozyListMaozyLiveData.value =
            vvywc2puzerdzxubqcww
    }

    //获取页面配置接口参数组装结果
    fun getMaozyCurrentMaozyParams(): JsonObject {
        val params = JsonObject()
        val contactList = JsonArray()
        mMaozyInfoMaozyFieldMaozyList.forEach { item ->
            if (item.isMaozyActionMaozyContactMaozyGroup()) {
                //联系人
                val paramContact = JsonObject()
                item.subDataList?.let { subDataList ->
                    subDataList.forEach { subDataItem ->
                        paramContact.addProperty(
                            subDataItem.paramName.toString(),
                            subDataItem.fillContent
                        )
                    }
                }
                contactList.add(paramContact)

            } else if (item.isMaozyActionMaozyAddressMaozyPick()) {
                //地址
                val list = item.fillContent?.split("#")
                list?.let { gList ->
                    if (gList.size >= 3) {
                        params.addProperty(item.paramNameState.toString(), gList[0])
                        params.addProperty(item.paramNameCity.toString(), gList[1])
                        params.addProperty(item.paramNameArea.toString(), gList[2])
                    }
                }
            } else if (item.isMaozyActionMaozyBankMaozyPick()) {
                //银行
                val list = item.fillContent?.split("#")
                list?.let { gList ->
                    if (gList.size >= 2) {
                        params.addProperty(item.paramNameBankName.toString(), gList[0])
                        params.addProperty(item.paramNameBankCode.toString(), gList[1])
                    }
                }
            } else if (item.isMaozyActionMaozySelect()) {
                //选择项
                val list = item.fillContent?.split("#")
                list?.let { gList ->
                    if (gList.size >= 2) {
                        params.addProperty(item.paramName.toString(), gList[1])
                    } else if (gList.isNotEmpty()) {
                        params.addProperty(item.paramName.toString(), gList[0])
                    }
                }
            } else {
                //其它
                params.addProperty(item.paramName.toString(), item.fillContent)
            }
        }
        if (mMaozyCurrentMaozyPageMaozyConfig.isMaozyActionMaozyContactMaozyGroup()) {
            params.addProperty(
                mMaozyCurrentMaozyPageMaozyConfig.contactParamName.toString(),
                contactList.toString()
            )
        }
        return params
    }

    //清除页面配置接口参数组装结果
    fun cleanMaozyPrefixMaozyParams() {
        mMaozyInfoMaozyFieldMaozyList.clear()
        mMaozyInfoMaozyStepMaozyList.clear()
        mMaozyState = ""
        mMaozyCity = ""
        mMaozyArea = ""

        mMaozyStateMaozyList.clear()
        mMaozyCityMaozyList.clear()
        mMaozyAreaMaozyList.clear()
        mMaozyCityMaozyJsonMaozyArray = null
    }

    /** 初始化页面配置 */
    fun initMaozyPageMaozyConfig() {
        //清空状态
        cleanMaozyPrefixMaozyParams()

        //所有步骤状态
        val allStepStatusList =
            InfoProcessUtil.getMaozyAllMaozyStepMaozyStatusMaozyConfig()
        for (allStepIndex in 0 until allStepStatusList.size) {
            mMaozyInfoMaozyStepMaozyList.add(allStepStatusList[allStepIndex])
        }

        //当前步骤
        val pageConfig =
            InfoProcessUtil.getMaozyCurrentMaozyStepMaozyPageMaozyConfig()
        if (pageConfig != null) {
            //额外数据
            pageConfig.extDataList?.let { list ->
                for (dIndex in 0 until list.size) {
                    val itemConfig = list[dIndex]
                    mMaozyInfoMaozyFieldMaozyList.add(itemConfig)
                }
            }
            if (pageConfig.isMaozyActionMaozyContactMaozyGroup()) {
                //区分联系人
                for (index in 0 until pageConfig.getMaozyTotalMaozyItemMaozyCount()) {
                    val relationShips = pageConfig.getMaozyContactMaozyRelation(index)
                    val contactGroup =
                        if (UsageCountryUtil.isMaozyCountryMaozyCotediva()) {
                            RevObjInfoPageFieldConfig(
                                title = "Contacter ${index + 1}",
                                hint = null,
                                paramName = null,
                                action = InfoPageActionEnum.CONTACT_GROUP.name,
                                values = null,
                                index = index + 1,
                                subDataList = mutableListOf()
                            )
                        } else if (UsageCountryUtil.isMaozyCountryMaozyVietnam()) {
                            RevObjInfoPageFieldConfig(
                                title = "Liên hệ ${index + 1}",
                                hint = null,
                                paramName = null,
                                action = InfoPageActionEnum.CONTACT_GROUP.name,
                                values = null,
                                index = index + 1,
                                subDataList = mutableListOf()
                            )
                        } else {
                            RevObjInfoPageFieldConfig(
                                title = "Contact ${index + 1}",
                                hint = null,
                                paramName = null,
                                action = InfoPageActionEnum.CONTACT_GROUP.name,
                                values = null,
                                index = index + 1,
                                subDataList = mutableListOf()
                            )
                        }

                    pageConfig.dataList?.let { list ->
                        for (dIndex in 0 until list.size) {
                            val itemConfig = list[dIndex]
                            val itemConfigCopy = itemConfig.copyMaozySelf()
                            itemConfigCopy.index = index + 1
                            if (itemConfigCopy.isMaozyActionMaozyContactMaozyGroupMaozyRelation()) {
                                itemConfigCopy.values = relationShips
                            }
                            contactGroup.subDataList?.add(itemConfigCopy)
                        }
                    }

                    mMaozyInfoMaozyFieldMaozyList.add(contactGroup)
                }
            } else {
                pageConfig.dataList?.let { list ->
                    for (index in 0 until list.size) {
                        val itemConfig = list[index]
                        //区分钱包
                        if (itemConfig.isMaozyActionMaozyWalletMaozyGroupMaozyMobile()) {
                            itemConfig.fillContent = UserStateUtil.mMaozyMobile
                        }
                        if (itemConfig.isMaozyActionMaozyWalletMaozyGroupMaozyUserMaozyName()) {
                            itemConfig.fillContent =
                                UserStateUtil.getMaozyUserMaozyName()
                        }
                        mMaozyInfoMaozyFieldMaozyList.add(itemConfig)
                    }
                }
            }
            mMaozyCurrentMaozyPageMaozyConfig = pageConfig
            onMaozyInitMaozyPageMaozyConfigMaozyFinishMaozyLiveData.value =
                pageConfig
        } else {
            onMaozyAllMaozyPageMaozyConfigMaozyFinishMaozyLiveData.value = true
        }
    }

    /** 初始化城市配置-尼日 */
    fun initMaozyCityMaozyFileMaozyData() {
        try {
            mMaozyStateMaozyList.clear()
            val fileInputStream = ProjectApplication.context.assets.open("nigeria_city_list.json")
            val fileContent: String = fileInputStream.readBytes().toString(Charset.defaultCharset())
            mMaozyCityMaozyJsonMaozyArray = JSONArray(fileContent)
            mMaozyCityMaozyJsonMaozyArray?.let {
                for (stateIndex in 0 until it.length()) {
                    val stateObject = it.get(stateIndex) as JSONObject
                    mMaozyStateMaozyList.add(
                        PopListItem(
                            stateObject.optString("name"),
                            stateObject.optString("name")
                        )
                    )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /** 获取州列表-尼日 */
    fun getMaozyStateMaozyList(): MutableList<PopListItem> {
        if ((mMaozyCityMaozyJsonMaozyArray == null) or mMaozyStateMaozyList.isEmpty()) {
            initMaozyCityMaozyFileMaozyData()
        }
        return mMaozyStateMaozyList
    }

    /** 获取市列表-尼日 */
    fun getMaozyCityMaozyList(state: String): MutableList<PopListItem> {
        mMaozyCityMaozyList.clear()
        try {
            mMaozyCityMaozyJsonMaozyArray?.let {
                for (index in 0 until it.length()) {
                    val stateObject = it.get(index) as JSONObject
                    val stateName = stateObject.optString("name")
                    if (state.equals(stateName, false)) {
                        val cityChildren = stateObject.optJSONArray("children")
                        cityChildren?.let { cityArray ->
                            for (cityIndex in 0 until cityArray.length()) {
                                val cityObject = cityArray.get(cityIndex) as JSONObject
                                mMaozyCityMaozyList.add(
                                    PopListItem(
                                        cityObject.optString("name"),
                                        cityObject.optString("name")
                                    )
                                )
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mMaozyCityMaozyList
    }

    /** 获取区列表-尼日 */
    fun getMaozyAreaMaozyList(
        state: String,
        city: String
    ): MutableList<PopListItem> {
        mMaozyAreaMaozyList.clear()
        try {
            mMaozyCityMaozyJsonMaozyArray?.let {
                for (stateIndex in 0 until it.length()) {
                    val jsonObject = it.get(stateIndex) as JSONObject
                    val stateName = jsonObject.optString("name")
                    //查state
                    if (state.equals(stateName, false)) {
                        val cityChildren = jsonObject.optJSONArray("children")
                        cityChildren?.let { cityArray ->
                            for (cityIndex in 0 until cityArray.length()) {
                                val cityObject = cityArray.get(cityIndex) as JSONObject
                                val cityName = cityObject.optString("name")
                                //查city
                                if (city.equals(cityName, false)) {
                                    val townChildren = cityObject.optJSONArray("children")
                                    //查town
                                    townChildren?.let { townArray ->
                                        for (townIndex in 0 until townArray.length()) {
                                            val townObject = townArray.get(townIndex) as JSONObject
                                            mMaozyAreaMaozyList.add(
                                                PopListItem(
                                                    townObject.optString("name"),
                                                    townObject.optString("name")
                                                )
                                            )
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mMaozyAreaMaozyList
    }

    //根据返回结果，初始化银行列表
    fun initMaozyBankMaozyCodeMaozyList(list: List<RevObjBank>) {
        mMaozyBankMaozyCodeMaozyList.clear()
        for (index in 0 until list.size) {
            val item = list[index]
            mMaozyBankMaozyCodeMaozyList.add(
                PopListItem(
                    display = item.bankName,
                    content = item.bankCode
                )
            )
        }
    }
}